Ext.onReady(function() {

    Ext.SSL_SECURE_URL = "../ext/resources/images/default/s.gif";
    Ext.BLANK_IMAGE_URL = "../ext/resources/images/default/s.gif";
    //    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    var menuHeight = document.body.offsetHeight - 100;


    var showOnePanel = true;//设置主页面单窗口还是多窗口


    var tools = [
        {
            id:'refresh',
            qtip:'刷新',
            handler: function(e, target, panel) {
                if (panel.id == 'board') {
                    afficheGrid.store.reload();
                }
                if (panel.id == 'message') {
                    meetingNoticeGrid.store.reload();
                }
                if (panel.id == 'worklist') {

                }
                if (panel.id == 'info') {

                }
            }
        }
        //        , {
        //        id:'gear',
        //        qtip:'设置',
        //        handler: function() {
        //            //            Ext.Msg.alert('Message', 'The Settings tool was clicked.');
        //        }
        //    }
        //        , {
        //        id:'close',
        //        qtip:'关闭',
        //        handler: function(e, target, panel) {
        //            panel.ownerCt.remove(panel, true);
        //        }
        //    }
    ]   ;
    var afficheGrid = new AfficheGrid();
    // afficheGrid.store.load();
    var meetingNoticeGrid = new MeetingNoticeGrid();
    //meetingNoticeGrid.store.load();

    var centerTabPanel = new Ext.TabPanel({
        region:'center',
        id:'centerTabPanel',
        deferredRender:false,
        activeTab:0,
        margins:'0 5 0 0',
        plugins: new Ext.ux.TabCloseMenu(),
        resizeTabs:true,
        minTabWidth: 100,
        tabWidth:150,
        enableTabScroll:true,
        autoScroll:true,
        items:[{
            xtype:'portal',
            margins:'35 5 5 0',
            title: '系统公告预警信息',
            iconCls: 'tabs',
            autoScroll:true,
            items:[{
                columnWidth:.99,
                style:'padding:10px 0 10px 10px',
                items:[{
                    title: '预警或提醒信息',
                    id:'message',
                    layout:'fit',
                    tools: tools,
                    items:meetingNoticeGrid
                },{
                    title: '公告或通知信息',
                    id:'board',
                    layout:'fit',
                    tools: tools,
                    items:afficheGrid
                }]
            }
            ]
        }
        ],
        loadPage: function(href, cls, title) {
            var tabId = 'workPanel' + cls;
            var tab = this.getComponent(tabId);
            if (showOnePanel) {
                tabId = 'workPanel';
                tab = this.getComponent(tabId);
                if (tab) {
                    this.setActiveTab(tab);
                    tab.setTitle(title);
                    Ext.get('iframe-workPanel').dom.src = href;
                } else {
                    var pIn1 = this.add(new DocPanel({
                        id: tabId,
                        cclass : cls,
                        layout:'fit',
                        items: [ new IFrameComponent({ id: tabId, url: href }) ],
                        title: title,
                        iconCls: 'tabs'
                    }));
                    this.setActiveTab(pIn1);
                }
            } else {
                if (tab) {
                    this.setActiveTab(tab);
                } else {
                    var autoLoad = {url: href,scripts: true};
                    var p = this.add(new DocPanel({
                        id: tabId,
                        cclass : cls,
                        layout:'fit',
                        items: [ new IFrameComponent({ id: tabId, url: href }) ],
                        title: title,
                        iconCls: 'tabs'
                    }));
                    this.setActiveTab(p);
                }
            }
        }
        ,loadPageAlways: function(href, cls, title) {
            var tabId = 'workPanel' + cls;
            var tab = this.getComponent(tabId);
            if (tab) {
                this.setActiveTab(tab);
            } else {
                var autoLoad = {url: href,scripts: true};
                var p = this.add(new DocPanel({
                    id: tabId,
                    cclass : cls,
                    layout:'fit',
                    closable:true,
                    items: [ new IFrameComponent({ id: tabId, url: href }) ],
                    title: title,
                    iconCls: 'tabs'
                }));
                this.setActiveTab(p);
            }

        },
        loadHealthPage: function(href, cls, title,isNew) {
            // var tabId = 'workPanel' + cls;
            var tabId = 'workPanel_health' ;
            var tab = this.getComponent(tabId);
            if (showOnePanel&&isNew) {
                tabId = 'workPanel_health';
                tab = this.getComponent(tabId);
                if (tab) {
                    this.setActiveTab(tab);
                    tab.setTitle(title);
                    Ext.get('iframe-workPanel_health').dom.src = href;
                } else {
                    var pIn1 = this.add(new DocPanel({
                        id: tabId,
                        cclass : cls,
                        layout:'fit',
                        items: [ new IFrameComponent({ id: tabId, url: href }) ],
                        title: title,
                        iconCls: 'tabs'
                    }));
                    this.setActiveTab(pIn1);
                }
            } else {

                if (tab) {
                    this.setActiveTab(tab);
                    tab.setTitle(title);
                    Ext.get('iframe-workPanel_health').dom.src = href;
                } else {
                    var autoLoad = {url: href,scripts: true};
                    var p = this.add(new DocPanel({
                        id: tabId,
                        cclass : cls,
                        layout:'fit',
                        items: [ new IFrameComponent({ id: tabId, url: href }) ],
                        title: title,
                        iconCls: 'tabs'
                    }));
                    this.setActiveTab(p);
                }
            }
        }
    });

    IFrameComponent = Ext.extend(Ext.BoxComponent, {
        onRender : function(ct, position) {
            this.el = ct.createChild({tag: 'iframe',id: 'iframe-' + this.id, frameBorder: 0, src: this.url});
        }
    });

    DocPanel = Ext.extend(Ext.Panel, {
        closable: true,
        autoScroll:true,
        initComponent : function() {
            DocPanel.superclass.initComponent.call(this);
        },
        scrollToMember : function(member) {
            var el = Ext.fly(this.cclass + '-' + member);
            if (el) {
                var top = (el.getOffsetsTo(this.body)[1]) + this.body.dom.scrollTop;
                this.body.scrollTo('top', top - 25, {duration:.75, callback: this.hlMember.createDelegate(this, [member])});
            }
        },
        scrollToSection : function(id) {
            var el = Ext.getDom(id);
            if (el) {
                var top = (Ext.fly(el).getOffsetsTo(this.body)[1]) + this.body.dom.scrollTop;
                this.body.scrollTo('top', top - 25, {duration:.5, callback: function() {
                    Ext.fly(el).next('h2').pause(.2).highlight('#8DB2E3', {attr:'color'});
                }});
            }
        },
        hlMember : function(member) {
            var el = Ext.fly(this.cclass + '-' + member);
            if (el) {
                el.up('tr').highlight('#cadaf9');
            }
        }
    });

    new Ext.Viewport({
        layout:'border',
        items:[
            new Ext.BoxComponent({ // raw
                region:'north',
                el: 'north',
                height:25
            }),{
                region:'west',
                id:'west-panel',
                title:'区域卫生信息平台',
                split:true,
                width: 200,
                minSize: 175,
                maxSize: 400,
                collapsible: true,
                margins:'0 0 0 5',
                layout:'accordion',
                layoutConfig:{
                    animate:true
                },
                items: [{
                    title:'系统功能菜单',
                    border:false,
                    id:'menu1',
                    iconCls:'nav',
                    html:'<div id="tree-viewer" style="overflow:auto;height:' + menuHeight + ';border:0px solid #c3daf9;"></div>'
                },{
                    title:'个人健康档案',
                    border:false,
                    id:'menu2',
                    iconCls:'settings',
                    html:'<div id="tree-viewer-health-file" style="overflow:auto;height:' + menuHeight + ';border:0px solid #c3daf9;"></div>'
                }

                ]
            },
            centerTabPanel
        ]
    });

    Ext.Ajax.timeout = 90000;
    var tree;
    var root;
    if (!tree) {
        var Tree = Ext.tree;
        tree = new Tree.TreePanel(
            {
                el:'tree-viewer',
                autoScroll:true,
                animate:false,
                border:false,
                enableDD:false,
                containerScroll: true,
                rootVisible:false,
                draggable:false,
                lines:true,
                loader: new Tree.TreeLoader({
                    dataUrl:'../menu/buildPermissionMenuJSON.action?group='+healthGroup
                })
            }
        );
        root = new Tree.AsyncTreeNode({
            text: '根节点',
            draggable:false,
            id:'0'
        });
        tree.setRootNode(root);

        tree.on('click', function (node, e) {
            e.stopEvent();
            if (node.isLeaf()) {
                document.all('currentToOpenMenuId').value = node.id;
                //                if (node.id == 251)
                //                    centerTabPanel.loadPageAlways('incomingCall/input.jsp', 251, '来电业务信息添加');
                //                 else
                if(node.attributes.href=='default.jsp?onlineUser'){

                    onlineUserwin.show();

                }
                else
                    centerTabPanel.loadPage(node.attributes.href, node.id, node.text);
            } else {
                node.toggle();
            }
        });
    }
    tree.render();
    root.expand();

    var treeHealthFile;
    var rootHealthFile;
    if (!treeHealthFile) {
        treeHealthFile = new Ext.tree.TreePanel(
            {
                el:'tree-viewer-health-file',
                id:'menutreehealth',
                autoScroll:true,
                cls: 'x-tree-node_blue',
                animate:false,
                border:false,
                enableDD:false,
                containerScroll: true,
                rootVisible:false,
                draggable:false,
                lines:true,
                loader: new Ext.tree.TreeLoader({
                    // 不带权限
                    //dataUrl:'../menu/buildPermissionMenuHealthFileJSON.action'
                    //根据角色来构建 hezn
                    dataUrl:'../menu/buildPartMenuHealthFileJSON.action?group='+healthGroup +'&idcard='+_queryIdcard
                })
            }
        );
        rootHealthFile = new Ext.tree.AsyncTreeNode({
            text: '根节点',
            draggable:false,
            id:'0'
        });
        treeHealthFile.setRootNode(rootHealthFile);

        treeHealthFile.on('click', function (node, e) {
            e.stopEvent();
            if (node.isLeaf()) {
                document.all('currentToOpenMenuId').value = node.id;
                centerTabPanel.loadHealthPage(node.attributes.href, node.id+ 55555, node.text,false);
            } else {
                node.toggle();
            }
        });
    }
    // treeHealthFile.render();
    treeHealthFile.render(Ext.get('tree-viewer-health-file'));
    rootHealthFile.expand();

    alert('ddd')
    changeMenuWithPermission(_queryIdcard)
    alert('ddd1111')
    var userList = function  () {
        onlineUserwin.show();
    }
    var changeTheme = function () {
        changeThemewin.show();
    }
    var changePassword = function () {
        changePasswordwin.show();
    }


    var changeThemeHref = Ext.get('changeThemeHref');
    changeThemeHref.on('click', changeTheme);

    //var onlineUserHref = Ext.get('onlineUserHref');
    // onlineUserHref.on('click', userList);

    var changePwdHref = Ext.get('changePwdHref');
    changePwdHref.on('click', changePassword);


    Ext.apply(Ext.form.VTypes, {
        password: function(val, field) {
            if (field.initialPassField) {
                var pwd = Ext.getCmp(field.initialPassField);
                return (val == pwd.getValue());
            }
            return true;
        },
        passwordText: '两次输入的密码不一致'
    });
    var pass1 = new Ext.form.TextField({
        fieldLabel: '新密码',
        name: 'pass',
        allowBlank:false,
        width: 125,
        minLength:6,
        inputType: 'password',
        id: 'pass'
    })
    var pass2 = new Ext.form.TextField({
        fieldLabel: '确认新密码',
        name: 'pass-cfrm',
        vtype: 'password',
        allowBlank:false,
        width: 125,
        minLength:6,
        inputType: 'password',
        initialPassField: 'pass'
    })
    var changePasswordFormPanel;
    if (!changePasswordFormPanel) {
        changePasswordFormPanel = new Ext.FormPanel({
            labelWidth: 100,
            labelAlign:'right',
            frame: true,
            bodyStyle:'padding:55px',
            url: '../user/changePassword.action',
            items: [ pass1,pass2]
        });
    }

    var changePasswordwin;
    if (!changePasswordwin) {
        changePasswordwin = new Ext.Window({
            title: '修改用户密码',
            id:'changePasswordwin',
            closable: true,
            closeAction : 'hide',
            collapsible:true,
            resizable:false,
            width: 400,
            height:300,
            layout: 'fit',
            plain:true,
            bodyStyle:'padding:5px;',
            maximizable : false,
            buttonAlign:'center',
            items: changePasswordFormPanel,
            buttons: [{
                text: '修改',
                handler: function() {
                    if (changePasswordFormPanel.getForm().isValid()) {
                        var ct = pass1.getValue();
                        ct = ct.trim();
                        if (ct.length == 0) {
                            Ext.Msg.alert('提示', '请输入正确密码格式，不能使用全空格密码！');
                            return;
                        }
                        changePasswordFormPanel.getForm().submit({
                            waitMsg: '正在处理，请稍等...',
                            reset: true,
                            failure: function(form, action) {
                                Ext.MessageBox.hide();
                                Ext.Msg.show({
                                    title: '错误',
                                    msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + action.result.msg + '</span>',
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.WARNING
                                });
                            },
                            success: function(form, action) {
                                Ext.MessageBox.hide();
                                Ext.Msg.show({
                                    title: '成功',
                                    msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + action.result.msg + '</span>',
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.INFO
                                });
                            },
                            method:'POST'
                        });
                    }
                }
            },{
                handler: function() {
                    changePasswordwin.hide();
                },
                text: '关闭'
            }
            ]
        });
    }

    var path = window.location.pathname;
    path = path.substring(0, path.lastIndexOf('/'));
    path = path.substring(0, path.lastIndexOf('/') + 1);
    var themeStore = new Ext.data.SimpleStore({
        fields: ['value', 'label'],
        data : [
            [path + 'ext/resources/css/ext-all.css','默认'],
            [path + 'resources/css/xtheme-darkgray.css', '暗灰'],
            [path + 'resources/css/xtheme-olive.css', '绿色'],
            [path + 'resources/css/xtheme-purple.css', '紫色'],
            [path + 'resources/css/xtheme-slate.css', '暗蓝']

        ]
    });
    //    [path + 'resources/css/xtheme-black.css', '黑色'],
    //            [path + 'resources/css/xtheme-slickness.css', '黑白']
    var themeComboBox = new Ext.form.ComboBox({
        fieldLabel:'页面风格',
        store: themeStore,
        displayField:'label',
        valueField:'value',
        typeAhead: true,
        editable:false,
        mode: 'local',
        triggerAction: 'all',
        selectOnFocus:true,
        value:path + 'ext/resources/css/ext-all.css',
        width:125
    });
    themeComboBox.on('select', function() {
        document.all('currentTheme').value = themeComboBox.value;
        Ext.util.CSS.swapStyleSheet('theme', themeComboBox.value);
    });
    var changeThemeFormPanel
    if (!changeThemeFormPanel) {
        changeThemeFormPanel = new Ext.FormPanel({
            labelWidth: 100,
            labelAlign:'right',
            frame: true,
            bodyStyle:'padding:65x;',
            items: [themeComboBox]
        });
    }
    var changeThemewin ;
    if (!changeThemewin) {
        changeThemewin = new Ext.Window({
            title: '设置页面风格样式',
            id:'changeThemewin',
            closable: true,
            closeAction : 'hide',
            collapsible:true,
            resizable:false,
            width: 400,
            height:300,
            layout: 'fit',
            plain:true,
            bodyStyle:'padding:5px;',
            maximizable : false,
            buttonAlign:'center',
            items: changeThemeFormPanel,
            buttons: [{
                handler: function() {
                    changeThemewin.hide();
                },
                text: '关闭'
            }
            ]
        });
    }

    var onlineUserwin ;
    var autoShowChatWin = function(msg) {
        var currentWin = Ext.getCmp(msg.fromPerId + msg.fromName);
        if (currentWin != null) {
            return null;
        }
        new ExtFrame.ui.ChatWin(msg.fromPerId, msg.fromName, msg.toPerId, msg.toName, 'PER', msg.qtip).init();
    }

    // 定时从服务器端获取消息，刷新时间为3秒钟
    var loadMsg = function() {
        Ext.Ajax.request({
            url : '../userMessage/getMSG.action',
            params : {
                toPerId : currentPerId
            },
            success : function(response) {
                if (response.responseText != '') {

                    var msg = eval(response.responseText);

                    for (var i = 0; i < msg.message.length; i++) {

                        autoShowChatWin(msg.message[i]);

                        addMsg(msg.message[i]);
                    }
                }
                setTimeout(loadMsg, 1000 * 3);
            }
        });

    }

   // loadMsg();
    var addMsg = function(msg) {
        var formatmsg = "<div class='_msgtitle' style='color:blue'>"
            + msg.fromName + "  " + msg.msgTime
            + "</div><div class='_msg'>" + decodeURIComponent(msg.msgBody)
            + "</div>";
        Ext.getCmp(msg.fromPerId + msg.fromName).findById("showMsg").body.insertHtml(
            "beforeEnd", formatmsg);
        Ext.getCmp(msg.fromPerId + msg.fromName).findById("showMsg").body.scroll("bottom",
            9999);
    }
    var treeDoubleClick1 = function(node, e) {
        if (node.attributes.perId == currentPerId) {
            return null;
        }
        new ExtFrame.ui.ChatWin(node.attributes.perId, node.text, currentPerId, currentUsername, 'PER', node.attributes.qtip + '—' + node.text).init();
    }
    var treeDoubleClick2 = function(node, e) {
        //        if (!node.isLeaf()) return null;
        if (node.attributes.idInDB == currentPerId) {
            return null;
        }
        new ExtFrame.ui.ChatWin(node.attributes.idInDB, node.text, currentPerId, currentUsername,
            node.attributes.typeString, node.attributes.qtip).init();
    }
    var comboxWithTree = new Ext.form.ComboBox({
        store:new Ext.data.SimpleStore({fields:[],data:[
            []
        ]}),
        editable:false,
        mode: 'local',
        triggerAction:'all',
        maxHeight: 200,
        width:200,
        tpl: " <div style='height:200px'><div id='treeZ'></div></div> ",
        selectedClass:'',
        onSelect:Ext.emptyFn,
        value:currentThemeGBCodeAndName
    });

    //省、市、县用——地区下拉树从省开始可选择到乡镇
    //乡镇及村用用——地区下拉树则从县区开始向下选择到乡镇 hezn 2010-12
    if(currentThemeGBCodeAndName.substr(6,2)!='00'){

        var treeLoader = new Ext.tree.TreeLoader({
            dataUrl:'../district/buildTreeDistrictJSON.action?level=6&districtCode='+currentThemeGBCodeAndName.substr(0,6)+'0000'
        });
    }
    else{
        var treeLoader = new Ext.tree.TreeLoader({
            dataUrl:'../district/buildTreeDistrictJSON.action?level=5&districtCode=3200000000'
        });
    }
    var treeZ = new Ext.tree.TreePanel({
        loader:treeLoader,
        border:false,
        rootVisible:false,
        root:new Ext.tree.AsyncTreeNode({text: '根目录',id:'0'})
    });
    treeZ.on('click', function(node, e) {
        comboxWithTree.setValue(node.id + node.text);
        reloadusertree();
        e.stopEvent();
        comboxWithTree.collapse();
    });
    comboxWithTree.on('expand', function() {
        treeZ.render('treeZ');
        treeZ.getRootNode().expand(false, true, function() {
            if (treeZ.getRootNode().firstChild) {
                treeZ.getRootNode().firstChild.expand(false, true);
            }
        });
    });


    function reloadusertree() {
        var tree = Ext.getCmp('im-tree-all');
        tree.getLoader().dataUrl=encodeURI('../user/buildAllUserTreeJSON.action?districtCode='+comboxWithTree.value);
        tree.body.mask('Loading', 'x-mask-loading');
        tree.root.reload();
        tree.root.collapse(true, false);
        tree.getRootNode().expand(false, true, function() {
            tree.body.unmask();
            if (tree.getRootNode().firstChild) {
                tree.getRootNode().firstChild.expand(false, true);
            }
        });
    }

    if (!onlineUserwin) {

        onlineUserwin = new Ext.Window({
            id: 'acc-win',
            title: '在线交流',
            width:250,
            height:400,
            iconCls: 'accordion',
            closeAction : 'hide',
            collapsible:true,
            shim:false,
            animCollapse:false,
            constrainHeader:true,
            maximizable : false,
            //            tbar:[{
            //                tooltip:{title:'Rich Tooltips', text:'Let your users know what they can do!'},
            //                iconCls:'connect'
            //            },'-',{
            //                tooltip:'Add a new user',
            //                iconCls:'user-add'
            //            },' ',{
            //                tooltip:'Remove the selected user',
            //                iconCls:'user-delete'
            //            }],

            layout:'accordion',
            border:false,
            layoutConfig: {
                animate:false
            },

            items: [
                new Ext.tree.TreePanel({
                    id:'im-tree',
                    title: '在线用户',
                    loader: new Ext.tree.TreeLoader({
                        dataUrl:'../user/buildOnlineUserJSON.action'
                    }),
                    rootVisible:false,
                    lines:false,
                    autoScroll:true,
                    tools:[{
                        id:'refresh',
                        on:{
                            click: function() {
                                var tree = Ext.getCmp('im-tree');
                                tree.body.mask('Loading', 'x-mask-loading');
                                tree.root.reload();
                                tree.root.collapse(true, false);
                                setTimeout(function() {
                                    tree.body.unmask();
                                    tree.root.expand(true, true);
                                }, 1000);
                            }
                        }
                    }],
                    root: new Ext.tree.AsyncTreeNode({
                        text:'在线用户',
                        id:'0'
                    }),
                    listeners: {
                        'dblclick':{fn:treeDoubleClick1}
                    }
                }),
                new Ext.tree.TreePanel({
                    id:'im-tree-all',
                    title: '全部用户',
                    loader: new Ext.tree.TreeLoader({
                        dataUrl:'../user/buildAllUserTreeJSON.action'
                    }),
                    rootVisible:false,
                    lines:false,
                    autoScroll:true,
                    tbar:[comboxWithTree],
                    tools:[{
                        id:'refresh',
                        on:{
                            click: function() {
                                reloadusertree;
                            }
                        }
                    }],
                    root: new Ext.tree.AsyncTreeNode({
                        text:'全部用户',
                        id:'0'
                    }),
                    listeners: {
                        'dblclick':{fn:treeDoubleClick2}
                    }
                })

            ]
        });
    }

    if(_passVaild!=''){
        // alert('dddd')
        alert('密码过于简单，请修改密码！');

        changePasswordwin.show()
    }

    function taskRun() {
        // if (afficheGridAutoRef)
        // afficheGrid.store.reload();
        // if (meetingNoticeGridAutoRef)
        // meetingNoticeGrid.store.reload();
    }
    var task = {run: taskRun, interval: 60 * 1000};
    var runner = new Ext.util.TaskRunner();
    //runner.start(task);

    var sss = Ext.get('ffff');
    sss.on('click', function(){changeMenuWithPermission('320622197811105437')});
    // sss.on('click', function(){changeTabPage('320622197811105437','','')});



});











